﻿#include "function_dl_line_9007.h"

FunctionDLLine9007::FunctionDLLine9007(QDialog* parent, QSettings* qsettings, QString section) : QDialog(parent)
{
    m_qsettings = qsettings;
    m_section = section;

    //m_model_image_path = QCoreApplication::applicationDirPath() + "/" + m_model_image_path;

    this->setWindowTitle(("AI检测"));
    QRect desktop_rect = QApplication::desktop()->geometry();
    double ratio_x = desktop_rect.width()/1920.0;
    double ratio_y = desktop_rect.height()/1080.0;

    move(0,0);
    setFixedSize(1920*ratio_x,1010*ratio_y);



    m_view = new QtQGraphicsView(this);
    m_view->setGeometry(660 * ratio_x, 0, 1000 * 1.25 * ratio_x, 800 * 1.25 * ratio_y);
   

    QSize control_size(120*ratio_x,40*ratio_y);

    QWidget* p = new QWidget(this);
    p->move(0*ratio_x,0*ratio_y);
    p->setFixedSize(600*ratio_x,800*ratio_y);

    QGridLayout *qgridLayout = new QGridLayout();
    p->setLayout(qgridLayout);

    int index = 0;

    QSize ButtonSize(160 * ratio_x, 40 * ratio_y);
    m_pushbutton_open_model = new QPushButton();
        m_pushbutton_open_model->setFixedSize(control_size);
        m_pushbutton_open_model->setText("设置模型地址");
        connect(m_pushbutton_open_model, &QPushButton::clicked, this, [=]() {
            QString filename;
            filename = QFileDialog::getOpenFileName(this,
                tr("选择模型"),
                "",
                tr("(*.proj)"));
            if (filename.isEmpty())
            {
                return;
            }
            RetrainedModelFileName = filename;
            m_qlabel_model_path->setText(RetrainedModelFileName);


        });

        qgridLayout->addWidget(m_pushbutton_open_model, index, 0);


        m_qlabel_model_path = new QLabel();
        m_qlabel_model_path->setText("");
        m_qlabel_model_path->setFixedSize(500 * ratio_x, 40 * ratio_y);
        qgridLayout->addWidget(m_qlabel_model_path, index, 1);
        index++;

		QLabel* p_qlabel;
		p_qlabel = new QLabel(this);
		p_qlabel->setText("标准面积");
		p_qlabel->setFixedSize(ButtonSize);
		qgridLayout->addWidget(p_qlabel, index, 0);
		m_qspinbox_standard_size = new QSpinBox();
		m_qspinbox_standard_size->setFixedSize(ButtonSize);
		m_qspinbox_standard_size->setMinimum(0);
		m_qspinbox_standard_size->setMaximum(10000000);
		qgridLayout->addWidget(m_qspinbox_standard_size, index, 1);
		index++;

		p_qlabel = new QLabel();
		p_qlabel->setText("比例");
		p_qlabel->setFixedSize(ButtonSize);
		qgridLayout->addWidget(p_qlabel, index, 0);
		m_qspinbox_ratio = new QDoubleSpinBox();
		m_qspinbox_ratio->setFixedSize(ButtonSize);
		m_qspinbox_ratio->setMinimum(0);
		m_qspinbox_ratio->setMaximum(1);
		qgridLayout->addWidget(m_qspinbox_ratio, index, 1);
		index++;


		
		p_qlabel = new QLabel();
		p_qlabel->setText("块最小高度");
		p_qlabel->setFixedSize(ButtonSize);
		qgridLayout->addWidget(p_qlabel, index, 0);
		m_qspinbox_height_min = new QSpinBox();
		m_qspinbox_height_min->setFixedSize(ButtonSize);
		m_qspinbox_height_min->setMinimum(10);
		m_qspinbox_height_min->setMaximum(10000);
		qgridLayout->addWidget(m_qspinbox_height_min, index, 1);
		index++;

		

    m_pushbutton_save_parameter = new QPushButton(this);
    m_pushbutton_save_parameter->setFixedSize(control_size);
    m_pushbutton_save_parameter->setText("保存参数");
    connect(m_pushbutton_save_parameter, &QPushButton::clicked, this, &FunctionDLLine9007::saveParameter);
    qgridLayout->addWidget(m_pushbutton_save_parameter, index,0);
    index++;

    m_pushbutton_show_orign_image = new QPushButton(this);
    m_pushbutton_show_orign_image->setFixedSize(control_size);
    m_pushbutton_show_orign_image->setText("显示原图");
    connect(m_pushbutton_show_orign_image, &QPushButton::clicked, this,[=]() {
        QImage q_image = matToQImage(m_image);
        m_view->setImage(q_image,"",Qt::green,40);
        return true;
    });
    qgridLayout->addWidget(m_pushbutton_show_orign_image, index,0);

    m_pushbutton_detection = new QPushButton(this);
    m_pushbutton_detection->setFixedSize(control_size);
    m_pushbutton_detection->setText("检测");
    connect(m_pushbutton_detection, &QPushButton::clicked, this, &FunctionDLLine9007::detectionImage);
    qgridLayout->addWidget(m_pushbutton_detection, index,1);
    index++;

    m_pushbutton_return = new QPushButton(this);
    m_pushbutton_return->setFixedSize(control_size);
    m_pushbutton_return->setText("退出");
    qgridLayout->addWidget(m_pushbutton_return, index, 0);
    connect(m_pushbutton_return, &QPushButton::clicked, this, [=]() {
        this->hide();
        });
	index++;
    

   

   

    loadParameter();

}

FunctionDLLine9007::~FunctionDLLine9007()
{
    ;
}
bool comparsion_DefectResult_y(DefectResult a, DefectResult b) {
	return a.rect.y < b.rect.y;
}

int FunctionDLLine9007::detection(Mat image, QString& message)
{
    m_image = image;
    if(image.empty())
    {
        message = "检测图像为空 ";
        return -1;
    }



    if(m_state==false)
    {
        return 0;
    }


    vector<vector<DefectResult>> result_all;
    m_dl->predictImage(image,result_all);

	vector_result.clear();

	if (result_all.size() == 0)
	{
		message = "没找到块 NG";
		return 0;
	}
	///第一步遍历一遍所有缺陷，找到未知的缺陷

	
	for (auto& obj : result_all[0]) {
		if (obj.height < m_height_min)
		{
			continue;
		}
		vector_result.push_back(obj);	
	}
	
	sort(vector_result.begin(), vector_result.end(), comparsion_DefectResult_y);
	
	

	if (vector_result.size() < 4)
	{
		message = "找到块数量不到4";
		return 0;
	}
	if (vector_result[0].rect.y < 5)
	{
		vector_result.erase(vector_result.begin());
	}
	
	vector_ng_result.clear();
	for (int index = 0; index < 4;index++) {
		double value = vector_result[index].area;
		
//		message += "\n像素面积" + QString::number(value) ;
        message +=        + "\n百分比" + QString::number(value / m_standard_size*100);
		if (value < m_standard_size*m_ratio)
		{
			vector_ng_result.push_back(vector_result[index]);
//			message += "小于标准面积*比例" + QString::number(m_standard_size*m_ratio);

		}
	}
	if (vector_ng_result.size() > 0)
	{

		return false;
	}
}

void FunctionDLLine9007::detectionImage()
{
    if(m_image.empty())
       {
           QMessageBox::information(nullptr,"","没有图像");
           return;
       }

       QString message;


       bool state = detection(m_image, message);



       Mat image_show;

       draw(m_image,image_show);

       QImage q_image = matToQImage(image_show);
       if (!q_image.isNull())
       {
           if(state)
                m_view->setImage(q_image, message + "OK",Qt::green,20);
           else
               m_view->setImage(q_image, message + "NG", Qt::red, 20);
       }

}

void FunctionDLLine9007::draw(Mat image_in, Mat& image_out)
{
	image_out = image_in.clone();
    if (image_out.channels() == 1)
    {
        cvtColor(image_out, image_out, COLOR_GRAY2BGR);
    }

	int index=0;
	for (auto obj : vector_result)
	{
		
		if (index>= 4)
		{
			break;
		}
        drawContours(image_out, obj.contour, -1, Scalar(0, 255, 0), 1);
		index++;
	}
	/*index = 0;
    for (auto obj : vector_result)
    {
		
		if (index >= 4)
		{
			break;
		}
        rectangle(image_out,obj.rect, Scalar(0, 255, 0),1);
		index++;
    }*/

	vector_result.clear();

	for (auto obj : vector_ng_result)
	{
		drawContours(image_out, obj.contour, -1, Scalar(0, 0, 255), 1);
	}
	vector_ng_result.clear();
}

void FunctionDLLine9007::loadParameter()
{
    try
    {
        RetrainedModelFileName = m_qsettings->value(m_section + "/" + "RetrainedModelFileName","").toString();


		m_height_min = m_qsettings->value(m_section + "/" + "m_height_min", 10000).toInt();
		m_ratio = m_qsettings->value(m_section + "/" + "m_ratio", 10000).toDouble();


        m_qlabel_model_path->setText(RetrainedModelFileName);

		m_qspinbox_height_min->setValue(m_height_min);
		m_qspinbox_ratio->setValue(m_ratio);

		m_standard_size = m_qsettings->value(m_section + "/" + "m_standard_size", 1).toInt();
		m_qspinbox_standard_size->setValue(m_standard_size);

    }
    catch(exception& error)
    {
        QMessageBox::critical(nullptr,error.what() , m_section + "参数需要重新设置");
    }





    return ;
}

void FunctionDLLine9007::saveParameter()
{
    try
        {
            RetrainedModelFileName = m_qlabel_model_path->text();


            m_qsettings->setValue(m_section + "/" + "RetrainedModelFileName", RetrainedModelFileName);



			m_height_min = m_qspinbox_height_min->value();
			m_qsettings->setValue(m_section + "/" + "m_height_min", m_height_min);
			m_ratio = m_qspinbox_ratio->value();
			m_qsettings->setValue(m_section + "/" + "m_ratio", m_ratio);
			
			m_standard_size = m_qspinbox_standard_size->value();
			m_qsettings->setValue(m_section + "/" + "m_standard_size", m_standard_size);


        }
        catch(exception& error)
        {
            QMessageBox::critical(nullptr,error.what() , m_section + "参数需要重新设置");
        }
    


}

bool FunctionDLLine9007::showDialog()
{
    QImage q_image = matToQImage(m_image);
    m_view->setImage(q_image, "",Qt::green,40);
    return true;
}

void FunctionDLLine9007::loadmodel()
{
    m_dl = new AIDll();
    string message;
    string para_path  = RetrainedModelFileName.toLocal8Bit().toStdString();
    QString name = "test";
    vector<string> m_vector_node;
    m_vector_node.push_back(name.toLocal8Bit().toStdString());


    if(false == m_dl->loadPorjectFiles(para_path,m_vector_node, 1024, 1250, 3,message))
        QMessageBox::information(nullptr,"ai", QString::fromStdString(message));
	else
	{
		vector_dl_3.push_back(m_dl);
		m_state = true;
	}
	
}

